<h1><?php echo $this->pageTitle; ?></h1>
<?php echo $form->create('DeRH', array('url' => array('controller' => 'delivery_requests', 'action' => 'save'))); ?>

<div class="toolbar">
    <div id="tLeft">
        <?php
        if ($mode == 'add' || $mode == 'revise' || $mode == 'cancel' || $mode == 'release') {
            echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back')));
        } else {
            if (in_array($status_id, array(DeRStatus::ON_REQUEST))) {
                echo $this->element('toolbar', array('buttons' => array('add', array('revise' => array('model' => 'DeRH')), 'delivery_cancel', array('print' => array('model' => 'DeRH')), 'back')));
            } elseif ($status_id == DeRStatus::REQUEST_TO_CANCEL) {
                echo $this->element('toolbar', array('buttons' => array('save', 'add', array('print' => array('model' => 'DeRH')), 'delivery_cancel', 'back')));
            } elseif ($status_id == DeRStatus::ON_DELIVERY && $mode == 'edit') {
                echo $this->element('toolbar', array('buttons' => array(array('edit' => array('params' => $this->data['DeRH']['id'] . '/receive:true', 'icon' => 'receive', 'text' => 'Receive')), array('print' => array('model' => 'DeRH')), 'back')));
            } elseif ($status_id == DeRStatus::ON_DELIVERY && $mode == 'receive') {
                echo $this->element('toolbar', array('buttons' => array('save', 'back')));
            } elseif ($this->data['DeRH']['is_returned']) {
                echo $this->element('toolbar', array('buttons' => array('save', 'add', array('print' => array('model' => 'DeRH')), 'back')));
            } elseif (in_array($status_id, array(DeRStatus::RECEIVED))) {
                echo $this->element('toolbar', array('buttons' => array('delivery_released', array('print' => array('model' => 'DeRH')), 'back')));
            } else {
                echo $this->element('toolbar', array('buttons' => array('add', array('print' => array('model' => 'DeRH')), 'back')));
            }
        }
        ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'DeRH', 'title' => 'request_no')); ?></div>
</div>

<?php echo $form->input('DeRH.id'); ?>
<?php echo $form->hidden('mode', array('value' => $mode, 'id' => 'mode', 'name' => 'data[mode]')); ?>
<?php
if ($mode == 'add' || $mode == 'revise') {
    echo $form->hidden('customer_id', array('id' => 'DeRHCustomerId', 'value' => $customer_id));
    echo $form->hidden('site_id', array('id' => 'DeRHSiteId', 'value' => $site_id));
}
?>
<fieldset>
    <table>
        <tr>
            <td width="120px"><?php echo $form->label('DeRH.request_no', 'Request no'); ?></td>
            <td width="250px">
                <?php
                if ($mode != 'add') {
                    echo $html->tag('span', $this->data['DeRH']['request_no']);
                    echo $form->hidden('DeRH.request_no');
                    if ($this->data['DeRH']['is_returned']) {
                        echo $html->link(' ' . ($this->data['DeRtH']['delivery_return_status_id'] == DeRtStatus::RETURNING ? $html->image('icon/return2.png') : $html->image('icon/return.png')), array('controller' => 'delivery_returns', 'action' => 'view', 'delivery_request_head_id:' . $this->data['DeRH']['id']), array('target' => '_blank'), null, false);
                    }
                }
                ?>
            </td>
            <td width="160px"><?php echo $form->label('DeRH.supplier_id', 'Vendor'); ?></td>
            <td>
                <?php
                if ($mode == 'add') {
                    echo $form->select('DeRH.supplier_id', $suppliers);
                } else {
                    echo $this->data['Supplier']['name'];
                    echo $form->hidden('DeRH.supplier_id');
                }
                echo $form->hidden('DeRH.supplier_id', array('id' => 'hidDeRHSupplierId'));
                ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRH.request_date', 'Request date'); ?></td>
            <td>
                <?php
                if ($mode == 'add') {
                    echo $html->tag('span', $today);
                    echo $form->hidden('DeRH.request_date', array('id' => 'request_date', 'value' => $today));
                } else {
                    echo $html->tag('span', $this->data['DeRH']['request_date']);
                    echo $form->hidden('DeRH.request_date');
                }
                ?>
            </td>
            <td><?php echo $form->label('DeRH.end_user', 'End User', array('class' => 'required')); ?></td>
            <td>
                <?php
                if ($mode == 'add' || $mode == 'revise') {
                    echo $form->text('DeRH.end_user');
                } else {
                    echo $html->tag('span', $this->data['DeRH']['end_user']);
                }
                ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRH.request_by', 'Request by'); ?></td>
            <td>
                <?php
                if ($mode == 'add') {
                    echo $html->tag('span', $request_by);
                    echo $form->hidden('DeRH.request_by', array('value' => $request_by));
                } else {
                    echo $html->tag('span', $this->data['DeRH']['request_by']);
                    echo $form->hidden('DeRH.request_by');
                }
                ?>
            </td>
            <td><?php echo $form->label('DeRH.customer_document_no'); ?></td>
            <td>
                <?php
                if ($mode == 'add' || $mode == 'revise') {
                    echo $form->text('DeRH.customer_document_no');
                } else {
                    echo $html->tag('span', $this->data['DeRH']['customer_document_no']);
                }
                ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRH.deliver_status_id', 'Delivery Status'); ?></td>
            <td><?php echo ($mode == 'add' ? 'On Request' : ($this->data['DeRStatus']['title'] . ($this->data['DeRH']['is_partial'] ? ' (Partial)' : ''))); ?></td>
            <td><?php echo $form->label('DeRH.due_date', 'Request Delivery Date', array('class' => 'required')); ?></td>
            <td>
                <?php
                if ($mode == 'add' || $mode == 'revise') {
                    echo $form->text('DeRH.due_date');
                } else {
                    echo $html->tag('span', $this->data['DeRH']['due_date']);
                }
                ?>
            </td>
        </tr>
        <?php if ($mode == 'edit') : ?>
            <tr>
                <td colspan="2">&nbsp;</td>
                <td><?php echo $form->label('DeRH.supplier_due_date', 'Actual Delivery Date'); ?></td>
                <td>
                    <?php echo empty($this->data['DeRH']['supplier_due_date']) ? '-' : $this->data['DeRH']['supplier_due_date']; ?>
                </td>
            </tr>
        <?php endif; ?>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th width="35px">No</th>
                <th width="200px">Part no.</th>
                <th width="120px">Stock code</th>
                <th>Description</th>
                <th width="120px">Request Qty.</th>
                <?php if ($status_id >= DeRStatus::ON_DELIVERY) { ?>
                        <!--                    <th width="90px">Delivery Qty.</th>-->
                    <th width="90px">Receive Qty.</th>
                <?php } ?>
                <th width="50px">Unit</th>
                <th width="80px">Price / Unit</th>
                <th width="80px">Amount</th>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
                <?php
            else :
                $count = count($this->data['DeR']);
                $total = 0;
                ?>
                <?php for ($i = 0; $i < $count; ++$i) : ?>
                    <tr class="<?php echo (($i + 1) % 2 == 0) ? 'even-cell' : 'odd-cell'; ?>">
                        <td><span><?php echo $i + 1; ?></span></td>
                        <td>
                            <?php
                            echo $html->link($this->data['DeR'][$i]['Product']['supplier_part_no'], '/supplier_inventories/view/' . $this->data['DeR'][$i]['cust_product_site_id'] . '/' . strtotime('now'), array('target' => '_blank', 'id' => 'DeR' . $i . 'PartNoSpan'));
                            // mode revise ไม่ต้องใช้ id
                            if ($mode != 'revise') {
                                echo $form->hidden("DeR.{$i}.id");
                            }
                            ?>
                        </td>
                        <td class="center">
                            <span id="DeR<?php echo $i; ?>StockCode"><?php echo $this->data['DeR'][$i]['CustProductSite']['stock_code']; ?></span>
                            <?php
                            echo $form->hidden("DeR.{$i}.product_id");
                            echo $form->hidden("DeR.{$i}.cust_product_site_id");
                            ?>
                        </td>
                        <td>
                            <?php
                            echo!empty($this->data['DeR'][$i]['CustProductSite']['text']) ?
                                    $this->data['DeR'][$i]['CustProductSite']['text'] :
                                    $this->data['DeR'][$i]['Product']['text'];
                            ?>
                        </td>
                        <td class="<?php echo $mode == 'revise' ? '' : 'text-right'; ?>">
                            <?php
                            if ($mode == 'revise') {
                                echo $form->text("DeR.{$i}.request_qty", array('maxlength' => 3, 'size' => 3, 'class' => 'text-right', 'no' => $i));
                                echo $html->tag('span', '/' . ($this->data['DeR'][$i]['CustProductSite']['supplier_current_stock'] + $this->data['DeR'][$i]['request_qty']), array('id' => "DeR{$i}MaxQty"));
                            } else {
                                echo $html->tag('span', $this->data['DeR'][$i]['request_qty'], array('id' => "DeR{$i}RequestQty"));
                            }
                            $qty = $this->data['DeR'][$i]['request_qty'];
                            ?>
                        </td>
                        <?php if ($status_id >= DeRStatus::ON_DELIVERY) { ?>
                                <!--                            <td class="text-right" id="<?php echo "DeR{$i}DeliveryQty"; ?>">
                            <?php
                            echo $this->data['DeR'][$i]['delivery_qty'];
                            $qty = $this->data['DeR'][$i]['delivery_qty'];
                            ?>
                                                    </td>-->
                            <td class="text-right">
                                <?php
                                if ($mode == 'receive') {
                                    echo $form->text("DeR.{$i}.receive_qty", array('value' => $this->data['DeR'][$i]['delivery_qty'], 'maxlength' => 3, 'size' => 5, 'class' => 'text-right'));
                                } else {
                                    if ($this->data['DeR'][$i]['receive_qty'] == null) {
                                        echo '-';
                                    } else {
                                        echo $this->data['DeR'][$i]['receive_qty'];
                                        $qty = $this->data['DeR'][$i]['receive_qty'];
                                    }
                                }
                                ?>
                            </td>
                        <?php } ?>
                        <td class="center"><?php echo $this->data['DeR'][$i]['Product']['Unit']['title']; ?></td>
                        <td class="text-right">
                            <span id="spanDeR<?php echo $i; ?>Price"><?php echo number_format($this->data['DeR'][$i]['price'], 2); ?></span>
                            <?php echo $form->hidden("DeR.{$i}.price"); ?>
                        </td>
                        <td class="text-right">
                            <?php
                            $amount = $qty * $this->data['DeR'][$i]['price'];
                            $total += $amount;
                            echo $html->tag('span', number_format($amount, 2), array('id' => "DeR{$i}Amount"));
                            ?>
                        </td>
                        <?php if ($mode == 'revise') : ?>
                            <td><?php echo $html->link($html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')), '#', array('id' => "linkDeR{$i}Delete"), null, false); ?></td>
                        <?php endif; ?>
                    </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
        <tfoot id="tableFooter">
            <tr>
                <?php
                if ($status_id >= DeRStatus::ON_DELIVERY) {
                    $colspan = 8;
                } else {
                    $colspan = 7;
                }
                ?>
                <td class="text-right" colspan="<?php echo $colspan; ?>">Total</td>
                <td class="text-right">
                    <span id="spanTotal">
                        <?php echo $mode != 'add' ? number_format($total, 2) : ''; ?>
                    </span>
                </td>
                <?php if ($mode == 'add' || $mode == 'revise') : ?>
                    <td>&nbsp;</td>
                <?php endif; ?>
            </tr>
        </tfoot>
    </table>
</fieldset>
<fieldset>
    <table>
        <tr>
            <td width="130px" class="top"><?php echo $form->label('DeRH.customer_comment', 'Customer Remark'); ?></td>
            <td>
                <?php
                if ($status_id != DeRStatus::REVISED && ($mode == 'add' || $mode == 'revise' || $mode == 'cancel' || $mode == 'release')) {
                    echo $form->textarea('DeRH.customer_comment', array('cols' => 50, 'rows' => 2));
                } else {
                    echo empty($this->data['DeRH']['customer_comment']) ? '-' : $this->data['DeRH']['customer_comment'];
                }
                ?>
            </td>
        </tr>
        <?php if ($mode == 'edit') { ?>
            <tr>
                <td class="top"><?php echo $form->label('DeRH.supplier_comment', 'Vendor Remark'); ?></td>
                <td><?php echo empty($this->data['DeRH']['supplier_comment']) ? '-' : $this->data['DeRH']['supplier_comment']; ?> </td>
            </tr>
            <?php if ($status_id > DeRStatus::ON_DELIVERY) { ?>
                <tr>
                    <td class="top"><?php echo $form->label('DeRH.is_invoiced', 'Invoiced'); ?></td>
                    <td>
                        <span id="spanInvoiced">
                            <?php echo $this->data['DeRH']['is_invoiced'] == true ? (!empty($this->data['DeRH']['invoice_no']) ? $this->data['DeRH']['invoice_no'] : 'Yes') : 'No'; ?>
                        </span>
                    </td>
                </tr>
            <?php }
        } ?>
    </table>
</fieldset>
<?php echo $form->end(); ?>

<script type="text/javascript">
    // JSON เก็บ part no ที่ป้อนเข้ามา อ้างไปยังลำดับแถว
    var partNos = {};

    /**
     * mode การทำงานของหน้าจอ add, edit, revise
     */
    var mode;

    requestDeR = function(event) {
        var e = $j(event.target);
        var no = e.attr("no");  // ลำดับแถวปัจจุบัน เริ่มที่ 0
        var part_no = $j.trim(e.val().toUpperCase());  // part no ที่ใส่เข้ามา

        // ไม่ได้ใส่อะไรเข้ามา
        if(part_no == "") { return; }

        // ถ้ายังไม่มี part no นี้อยู่
        if (partNos[part_no] == null) {
            $j('#hidDeRHSupplierId').val($j('#DeRHSupplierId').val());
            $j('#DeRHSupplierId').attr('disabled', true);

            var url = base + "/supplier_customer_inventories/json_find_by_supplier_part_no_site_id_supplier_id/";
            var params = {supplier_part_no: part_no, site_id: $j('#DeRHSiteId').val(), supplier_id: $j('#DeRHSupplierId').val()};
            postRequest(url, params, function(data) {
                if (!data.CustProductSite) {    // ไม่พบข้อมูล
                    e.val('');
                    alert("No product found.");
                    return;
                } else if (data.CustProductSite.supplier_current_stock == 0) { // ไม่มีสินค้าอยู่ใน stock
                    e.val('');
                    alert("There is no product left in vendor inventory.");
                    return
                    // ถ้า Request ไม่ถูก vendor
                }

                setRequest(data, no);

                // แสดงปุ่ม ลบแถว
                $j('#linkDeR' + no + 'Delete').show();

                // บันทึกแถวปัจจุบันของ part no
                partNos[data.Product.part_no] = no;
                partNos[data.Product.supplier_part_no] = no;
                partNos[data.CustProductSite.stock_code] = no;
                var nextRow = (parseInt(no) + 1);
                createRow(nextRow)
                $("DeR" + nextRow + "PartNo").focus();
            }
        );
        } else {
            e.val('');
            var row = partNos[part_no]; // แถวที่มี part_no นี้อยู่
            $j("#DeR" + row + "RequestQty").val(parseInt($j("#DeR" + row + "RequestQty").val()) + 1);
            setTimeout(function() {
                $j("#DeR" + no + "PartNo").focus();
            }, 100);
            checkRequestQty(row);
        }
    }

    checkRequestQty = function(no) {
        var maxQty = parseInt($j("#DeR" + no + "MaxQty").text().substring(1));
        var requestQty = parseInt($j("#DeR" + no + "RequestQty").val());
        if (requestQty < 1) {
            alert('Request quantity at least 1');
            $j("#DeR" + no + "RequestQty").val(1);
            requestQty = 1;
        }

        if (requestQty > maxQty) {
            alert("Please Request quantity less than max quantities")
            $j("#DeR" + no + "RequestQty").val(maxQty);
            requestQty = maxQty;
        }

        var price = parseFloat($j('#DeR' + no + 'Price' ).val());
        var amount = requestQty * price;
        $j("#DeR" + no + "Amount").text(amount.toFixed(2));

        var total = 0;
        // calculate total
        $j('span[id$=Amount]').each(function() {
            var amount = parseFloat($j.trim($j(this).text()).replace(',', ''));
            if (!isNaN(amount)) {
                total += amount;
            }
        });
        $j('#spanTotal').text(total.toFixed(2));
    };

    /**
     * กำหนดรายการ Request จากข้อมูลที่ดึงมาได้ตามแถวที่ระบุ
     */
    setRequest = function(data, no) {
        $j("#DeR" + no + "StockCode").text(data.CustProductSite.stock_code);
        $j("#DeR" + no + "PartNo").hide();
        $j("#linkDeR" + no + "ProductId").hide();
        $j("#DeR" + no + "PartNoSpan").text(data.Product.supplier_part_no).show();
        $j("#DeR" + no + "ProductId").val(data.CustProductSite.product_id);
        $j("#DeR" + no + "CustProductSiteId").val(data.CustProductSite.id);
        $j("#DeR" + no + "ProductText").text(data.CustProductSite.text != null? data.CustProductSite.text: data.Product.text);

        $j("#DeR" + no + "MaxQty").text("/" + data.CustProductSite.supplier_current_stock);
        $j("#DeR" + no + "RequestQty").val(1);

        $j("#DeR" + no + "ProductUnit").text(data.Product.Unit.title);
        $j("#DeR" + no + "PriceUnit").text(data.CustProductSite.price);
        $j("#DeR" + no + "Price").val(data.CustProductSite.price);
        checkRequestQty(no);
    }

    custProductSiteHandler = function(stock_code) {
        if (stock_code != null) {
            // หา input part no ที่ยังแสดงอยู่ (มีอันเดียวเสมอ)
            if ($j.browser.msie == true) {
                $j("input[id$=PartNo]:visible").val(stock_code).focus();
            } else {
                $j("input[id$=PartNo]:visible").val(stock_code).focus().blur();
            }
        }
    }

    function createRow(row) {
        var tBody = $("productRow");
        var tr = new Element("tr");
        tr.addClassName(((row + 1) % 2 == 0)? "even-cell" : "odd-cell");

        tr.update('<input id="DeR' + row + 'Id" type="hidden" value="" name="data[DeR][' + row + '][id]" />');

        var tdNo = new Element("td");
        tdNo.update('&nbsp;');
        tr.insert(tdNo);

        var tdPartNo = new Element("td");
        tdPartNo.insert('<input id="DeR' + row + 'PartNo" type="text" value="" no="' + row + '" name="data[DeR][' + row + '][part_no]"/>');
        tdPartNo.insert('<input id="DeR' + row + 'ProductId" type="hidden" value="" name="data[DeR][' + row + '][product_id]"/>');
        tdPartNo.insert('<input id="DeR' + row + 'CustProductSiteId" type="hidden" value="" name="data[DeR][' + row + '][cust_product_site_id]"/>');
        tdPartNo.insert('<span id="DeR' + row + 'PartNoSpan" style="display: none"></span>');
        tdPartNo.insert('&nbsp;<a href="#" id="linkDeR' + row + 'ProductId"><?php echo $html->image('icon/search.png'); ?></a>');
        tr.insert(tdPartNo);

        var tdStockCode = new Element("td", {'class': 'center'});
        tdStockCode.insert('<span id="DeR' + row + 'StockCode"></span>');
        tr.insert(tdStockCode);

        var tdTitle = new Element("td");
        tdTitle.insert('<span id="DeR' + row + 'ProductText"></span>');
        tr.insert(tdTitle);

        var tdRequestQty = new Element("td");
        var div = new Element("span", {'class': 'inline'});
        div.update('<input id="DeR' + row + 'RequestQty" no="' + row + '" class="text-right" type="text" value="" maxlength="3" size="3" name="data[DeR][' + row + '][request_qty]"/>');
        tdRequestQty.insert(div);
        tdRequestQty.insert('<span id="DeR' + row + 'MaxQty"></span>');
        tr.insert(tdRequestQty);

        var tdUnit = new Element("td", {'class': 'center'});
        tdUnit.insert('<span id="DeR' + row + 'ProductUnit"></span>');
        tr.insert(tdUnit);

        var tdPriceUnit = new Element("td", {'class': 'text-right'});
        tdPriceUnit.insert('<span id="DeR' + row + 'PriceUnit"></span>');
        tdPriceUnit.insert('<input id="DeR' + row + 'Price" type="hidden" value="" name="data[DeR][' + row + '][price]"/>');
        tr.insert(tdPriceUnit);

        var tdAmount = new Element("td", {'class': 'text-right'});
        tdAmount.insert('<span id="DeR' + row + 'Amount"></span>');
        tr.insert(tdAmount);

        var tdDelete = new Element("td", {"class": "center"});
        tdDelete.insert('<a href="#" id="linkDeR' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a>');
        tr.insert(tdDelete);

        tBody.insert(tr);
        $j('#productRow').runno();
        addRowListener(row);
    }

    function addRowListener(row, revised) {

        // mode add add event ทุก element ในแถว mode revise add เฉพาะ request_qty
        if (!revised) {
            $j("#DeR" + row + "PartNo").bind('keypress', partNoKeyPress);

            $j("#DeR" + row + "PartNo").bind('blur', function(event) {
                requestDeR(event);
            });

            $j("#linkDeR" + row + "ProductId").bind('click', function(event) {
                if ($j('#DeRHSupplierId').val() != '') {
                    requestPopup(base +  "/supplier_customer_inventories/popup_view/" + $j('#DeRHCustomerId').val() + '/' + $j('#DeRHSiteId').val() + '/' + $j('#DeRHSupplierId').val(), "custProductSiteHandler");
                } else {
                    alert('Please select a vendor');
                }
            });
        }

        $j("#DeR" + row + "RequestQty").bind('change', function() {
            checkRequestQty($j(this).attr('no'));
        });


        // ดักจับ Event กดลบแถว
        $j('#linkDeR' + row + 'Delete').bind('click', function() {
            // ลบรายการ part no ออกจาก list
            var p = $j("#DeR" + row + "PartNoSpan").text();
            var sc = $j("#DeR" + row + "StockCode").text();
            partNos[p] = undefined;
            partNos[sc] = undefined;

            // ลบ แถว
            $j('#DeR' + row + 'StockCode').parents('tr').remove();

            // จัดลำดับตัวเลขหน้าแถวใหม่
            $j('#productRow').runno();
        });
    };

    $j(function() {
        mode = $j('#mode').val();

        if (mode == 'add' || mode == 'revise') {
            var tr = $j("#productRow").children();
            var index = $j("#productRow").children().length;
            tr.each(function(i) {
                addRowListener(i, true);
                var part_no = $j('#DeR' + i + 'PartNoSpan').text();
                var stock_code = $j('#DeR' + i + 'StockCode').text();
                partNos[part_no] = i;
                partNos[stock_code] = i;
            });

            createRow(index);

            $j('#DeRHId').parent('form').beforeSubmit(function() {
                if (!$j.validateField('DeRHSupplierId', 'Vendor ', 'DeRHSupplierId')) {
                    return false;
                }
                if (!$j.validateField('DeRHEndUser', 'End User', 'DeRHEndUser')) {
                    return false;
                }
                if (!$j.validateField('DeRHDueDate', 'Delivery Date', 'DeRHDueDate')) {
                    return false;
                }
                if (!$j.validateColumns('RequestQty', 'Request Qty', {callback: $j.QTY})) {
                    return false;
                }
                // นับแถบใน product row ถ้ามีแค่ 1 แสดงว่ายังไม่ได้ add product ซักรายการ
                if ($j('#productRow').children().length == 1) {
                    if (!$j.validateField('DeR0PartNo', 'Product', 'DeR0PartNo')) {
                        return false;
                    }
                }
                return true;
            });

            $j('#DeRHDueDate').datepicker(datepicker_options);
        } else if (mode == 'receive') {

            // check receive qty ไม่เกิน delivery qty
            $j(':text[id$=ReceiveQty]').bind('keypress', partNoKeyPress);
            $j(':text[id$=ReceiveQty]').bind('change', function() {
                // cal Amount
                var maxQty = parseInt($j(this).parents('tr').find('[id$=RequestQty]').text());
                var receiveQty = parseInt($j(this).val());
                if (receiveQty < 0) {
                    alert('Receive quantity at least 0');
                    $j(this).val(0);
                    receiveQty = 0;
                }

                if (receiveQty > maxQty) {
                    alert("Please receive not greater than delivery quantity")
                    $j(this).val(maxQty);
                    receiveQty = masQty;
                }

                var price = parseFloat($j(this).parents('tr').find('[id$=Price]').text().replace(',', ''));
                var amount = receiveQty * price;
                $j(this).parents('tr').find('[id$=Amount]').text(amount.toFixed(2));

                // cal total
                var total = 0;
                $j('span[id$=Amount]').each(function() {
                    var amount = parseFloat($j.trim($j(this).text()).replace(',', ''));
                    if (!isNaN(amount)) {
                        total += amount;
                    }
                });
                $j('#spanTotal').text(total.toFixed(2));
            });
        }

    });
</script>